#!/bin/bash
#
# Copyright (c) Microsoft. All rights reserved.
#
# Licensed under the MIT license. See LICENSE.md file in the project root
# for full license information.
# ==============================================================================

. $TEST_ROOT_DIR/run-test-common

set -x -o pipefail -e

MODULE_DIR="$(python -c "import cntk, os, sys; sys.stdout.write(os.path.dirname(os.path.abspath(cntk.__file__)))")"

cd ../../../../bindings/python/doc

# Copy the notebooks to the local directory
cp ../../../Manual/Manual_* .
cp ../../../Tutorials/CNTK_* .
rm CNTK_5*.ipynb

if [ "$OS" == "Windows_NT" ]; then
  NORM_PATH="cygpath -aw --file -"
  # In our test env, DOS find.exe may come first in path, make sure we don't use it:
  FIND=/bin/find
else
  NORM_PATH=cat
  FIND=find
fi

sphinx-apidoc "$MODULE_DIR" --module-first --separate --no-toc --output-dir=. --force \
  $( ( printf "$MODULE_DIR/%s\n" cntk_py.py conftest.py internal; $FIND "$MODULE_DIR" -type d -name tests ) | $NORM_PATH)

sphinx-build -b html -d _build/doctrees -W -j $(nproc) . _build/html

#Remove the ipynb's
rm Manual_*.ipynb
rm CNTK_*.ipynb

# Note: there's currently no way to disable the below checks on a per-instance basis.
# If they yield false positives, they need to be refined, or disabled if this
# is not possible.

ERROR=0

# Exclude the CNTK_*.html and Manual_*.html since the rules below do not apply
# to content generated from ipynb files (Specifically Object addresses for Matplotlib
# and back-ticks in the notebook markdown text. 
rm _build/html/CNTK_*.html
rm _build/html/Manual_*.html

# (Using "grep -a" below because of Windows test environment setup.)
if grep -aE " at 0x[0-9a-fA-F]{8}" _build/html/*.html; then
  echo Object addresses leaked into documentation, please fix \(e.g., by
  echo   repeating the signature at the beginning of the docstring\).
  ((ERROR++))
fi

if grep -a '``' _build/html/*.html; then
  echo Double back-ticks leaked into the documentation. Please check.
  ((ERROR++))
fi

if grep -a ':[a-z][a-z]*:' _build/html/*.html; then
   echo Unrendered content leaked into the documentation. Please check.
   ((ERROR++))
fi

# TODO no BUGBUG or similar in rendered content

((ERROR == 0)) || {
  echo Error\(s\) occurred, stopping.
  false
}

set +x
echo "__COMPLETED__"
